<?php
require_once 'config.php';

session_start();

// 验证部门用户权限
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'department') {
    header("Location: index.html");
    exit();
}

$department = $_SESSION['department'];
$conn = getDBConnection();

// 处理添加人员
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_personnel'])) {
    $names = explode("\n", trim($_POST['names']));
    
    foreach ($names as $name) {
        $name = trim($name);
        if (!empty($name)) {
            $stmt = $conn->prepare("INSERT IGNORE INTO personnel (name, department) VALUES (?, ?)");
            $stmt->bind_param("ss", $name, $department);
            $stmt->execute();
        }
    }
}

// 处理删除人员
if (isset($_GET['delete_personnel'])) {
    $name = $_GET['delete_personnel'];
    
    // 标记历史记录为已删除
    $stmt = $conn->prepare("UPDATE status_history SET is_deleted = TRUE WHERE name = ?");
    $stmt->bind_param("s", $name);
    $stmt->execute();
    
    // 删除人员
    $stmt = $conn->prepare("DELETE FROM personnel WHERE name = ?");
    $stmt->bind_param("s", $name);
    $stmt->execute();
}

// 获取部门人员
$personnel = $conn->query("SELECT name, status FROM personnel WHERE department = '$department' ORDER BY name");

$conn->close();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $department; ?>部门管理</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="department-container">
        <h1><?php echo $department; ?>部门管理</h1>
        
        <div class="personnel-management">
            <h2>人员管理</h2>
            <form method="post">
                <div class="form-group">
                    <label for="names">人员姓名（每行一个）</label>
                    <textarea id="names" name="names" rows="5" required></textarea>
                </div>
                <button type="submit" name="add_personnel" class="btn">添加人员</button>
            </form>
            
            <h3>当前人员名单</h3>
            <ul class="personnel-list">
                <?php while ($row = $personnel->fetch_assoc()): ?>
                <li>
                    <?php echo $row['name']; ?>
                    <a href="?delete_personnel=<?php echo urlencode($row['name']); ?>" class="delete-btn">删除</a>
                </li>
                <?php endwhile; ?>
            </ul>
        </div>
        
        <div class="navigation">
            <a href="status.php" class="btn">状态管理</a>
            <a href="history.php" class="btn">历史记录</a>
            <a href="logout.php" class="logout-btn">退出登录</a>
        </div>
    </div>
</body>
</html>